Larave文件參考
先說說什麼是框架?
框架就像「建築的骨架」或「搭積木的底板」,提供一套固定的結構和規則,讓你可以在上面快速開發程式。
它不是程式本身的功能,而是幫你組織程式、管理流程、提供常用工具的基礎
用框架的好處:
原生 PHP:自己從零開始蓋房子,要自己做地基、牆壁、屋頂,每個細節都自己控制。
框架:房子已經有地基和骨架,你只需要建牆、裝門窗、布置房間,就可以快速完成。
簡單說:
框架 = 開發的骨架 + 常用工具集 + 規範流程
只要專注在專案「特色功能」,不必重複做基本底層工作。
Laravel 提供簡化路由:一行就可以把網址對應到程式功能
Route::get('/index', 'UserController@Hello');
這是Laravel基本的路由設定,就是根據MVC設計模式寫的路由
-> Route::get() → 定義一個 GET 請求的路由(訪問網址) *Laravel 提供的特殊固定寫法
-> '/index' → 當使用者訪問 /index 這個網址時
-> 'UserController@Hello' → Laravel 會呼叫 UserController 裡的 Hello() 方法來處理請求
Laravel 控制器寫法
namespace App\Http\Controllers;
use App\Models\User;
class UserController
{
public function Hello()
{
$users = User::all(); // 用 Eloquent ORM 取得資料表全部資料
return view('users', ['users' => $users]); // 傳給 View 顯示
}
}
->namespace App\Http\Controllers 「資料夾路徑」,告訴程式「這個 Controller 在哪裡」
->use App\Models\User 這行是 引入 User model,方便在 Controller 裡使用
Model 寫法
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
}
->Illuminate\Database\Eloquent\Model ,裡面封裝了很多跟資料庫互動的功能,引用的話就可以使用Laravel提供的ORM寫法
View 寫法
<h1>使用者列表</h1>
@foreach($users as $user)
<p>{{ $user->name }}</p>
@endforeach
Laravel 使用 Blade 模板語法,把 PHP 和 HTML 混合寫法簡化,更容易閱讀與維護
結語
Route:定義網址 /index,指向 UserController@Hello
Controller:接收請求,呼叫 Model 抓資料 $users = User::all(),然後傳給 View
Model:操作資料庫(Eloquent ORM)
View:顯示資料給使用者看
補充:Laravel 寫法會根據版本有略微不同 本文是根據5.4版本寫的